package com.lesama.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        // 1. 创建socket对象
        Socket socket = new Socket("127.0.0.1", 8888);

        // 2. 获取网络输入输出流
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();

        // 3. 将字节流封装为缓冲流
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

        // 4. 向服务端写文件名
        bw.write("miku.png");
        bw.newLine(); // 需要向服务器输出换行
        bw.flush(); // 同时强制刷新，保证读取不会卡死

        // 5. 向服务端上传文件
        String res = br.readLine();
        if(res.equals("ok")) {
            // 表示服务端接收成功
            File file = new File("D:\\photo\\miku.png");
            FileInputStream fis = new FileInputStream(file); // 文件输入流
            byte[] bytes = new byte[1024];
            int len;
            // 开始读取文件
            while((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len); // 向服务器写文件字节流
            }
            fis.close();
            // 至此文件上传完毕，socket向输入流传递结束信号
            socket.shutdownOutput();
        }

        // 6. 读取服务端成功的消息
        String msg = br.readLine();
        System.out.println(msg);

        // 7. 关闭socket
        socket.close();
    }
}
